/*
 * @Date         : 2024-05-12 17:44:11 星期0
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"

export const echoServiceImpl = {
  unaryEcho: (call, cb) => {
    const { name } = call.request

    if (name === "") {
      callback({
        code: grpc.status.INVALID_ARGUMENT,
        details: "request missing required field: name",
      })
      return
    }

    const response = { value: "Hello " + name }
    cb(null, response)
  },

  serverStreamingEcho: (call) => {
    const { name } = call.request

    if (name === "") {
      call.emit("error", {
        code: grpc.status.INVALID_ARGUMENT,
        details: "request missing required field: name end",
      })
      // 'error' 事件表示发生错误并且流已关闭。所以可以省略 end 调用
      // call.end()
      return
    }

    const hello = "Hello From Server"

    for (let i = 0; i < hello.length; i++) {
      call.write({ value: hello[i] })
    }

    call.end()
  },
}
